package com.meixiang.activity.moments;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.moments.MyPostAdapter;
import com.meixiang.entity.account.MyPostBean;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：黑哥 on 2016/5/7 11:25
 * <p/>
 * 我的帖子
 */
public class MyPostActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    private Activity mActivity;
    @Bind(R.id.swipe_target)
    RecyclerView mRecyclerView;

    private MyPostBean mBean;

    private MyPostAdapter mAdapter;

    private int pageNo = 1, pageSize = 10, totalPage = 0;

    private boolean isLoadMore; // 是否是加载更多


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_post);
        mActivity = MyPostActivity.this;
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle("我的帖子");
    }

    @Override
    protected void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new MyPostAdapter(mActivity,mActivity);
        mRecyclerView.setAdapter(mAdapter);


        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);

        /**检查RecyclerView是否滑动底部如果滑到*/
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
        });
    //Item的点击事件
        mAdapter.setOnItemClickListener(new MyPostAdapter.onItemClickListener() {

            @Override
            public void onLikeItemClick(View v, int position,TextView mTvLike) {
                //未点赞
                if (mAdapter.getData().get(position).getMyLaud().equals("0")) {
                    AddLaud(position,mTvLike);
                } else {
                    CancelLaud(position);
                }

            }

            @Override
            public void onCheckoutPositionItemClick(View v, int position) {
                Intent intent = new Intent(mActivity, PostDetailsActivity.class);
                intent.putExtra("commentId", mAdapter.getData().get(position).getCommentId());
                startActivity(intent);
            }

            @Override
            public void onMessageItemClick(View v, int position) {
                Intent intent = new Intent(mActivity, PostDetailsActivity.class);
                intent.putExtra("commentId", mAdapter.getData().get(position).getCommentId());
                intent.putExtra("comment", "1");
                startActivity(intent);
            }
        });

    }

    @Override
    protected void setData() {
        status.showLoading();
        getPostData(true);

    }

    private void getPostData(final boolean isPull) {
        HttpParams params = new HttpParams();
        params.put("pageSize", pageSize + "");
        params.put("pageNo", pageNo + "");
        HttpUtils.post(Config.ACCOUNT_MY_POST, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (isPull) {
                    mAdapter.clear();
                }
                List<MyPostBean> mList = AbJsonUtil.fromJson(result.optJSONArray("myPublishList").toString(), new TypeToken<List<MyPostBean>>() {
                });
                pageNo = result.optInt("pageNo");
                totalPage = result.optInt("totalPage");
                if (mList == null || mList.size() == 0) {
                    status.showNoData("暂无数据");
                } else {
                    status.removeView();
                    mAdapter.addAll(mList);
                }
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(mActivity, message);
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getPostData(isPull);
                    }
                });

                if (message.equals("暂无数据")) {
                    status.showNoData("暂无数据");
                } else {
                    status.showNoData(message, "重新加载", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            status.showLoading();
                            getPostData(isPull);
                        }
                    });
                }
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (mRefresh.isRefreshing()) {
                    mRefresh.setRefreshing(false);
                } else if (mRefresh.isLoadingMore()) {
                    mRefresh.setLoadingMore(false);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {

    }


    @Override
    public void onLoadMore() {
        if (pageNo<totalPage){
            pageNo++;
            getPostData(false);
        }else{
            AbToastUtil.showToast(activity, "已无更多内容");
            mRefresh.setLoadingMore(false);
        }

    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        getPostData(true);
    }


    //点赞
    private void AddLaud(final int position,final TextView mTvLike) {
        HttpParams params = new HttpParams();
        params.put("commentId", mAdapter.getData().get(position).getCommentId());
        HttpUtils.post(Config.MOMENTS_ADD_LAUD, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, message);
                Tool.Like(activity,mTvLike);
                MyPostBean moments = mAdapter.getData().get(position);
                moments.setMyLaud("1");
                moments.setLaudNumber((Integer.parseInt(moments.getLaudNumber()) + 1) + "");
                mAdapter.notifyItemChanged(position);
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }


    //取消点赞
    private void CancelLaud(final  int position){
        HttpParams params = new HttpParams();
        params.put("commentId",  mAdapter.getData().get(position).getCommentId());
        HttpUtils.post(Config.MOMENTS_CANCEL_LAUD, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, message);
                MyPostBean moments = mAdapter.getData().get(position);
                moments.setMyLaud("0");
                moments.setLaudNumber((Integer.parseInt(moments.getLaudNumber()) - 1) + "");
                mAdapter.notifyItemChanged(position);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(activity, message);
            }
        });
    }
}
